package com.maychat.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.maychat.config.Consts;
import com.maychat.exception.BusinessException;
import com.maychat.exception.CaptchaException;
import com.maychat.pojo.Result;
import com.maychat.service.UserInfoService;
import com.maychat.utils.RedisUtils;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/account")
public class LoginController {

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/code")
    public Result getCode() {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);
        String base64 = captcha.getImageBase64Data();
        String key = UUID.randomUUID().toString();
        redisUtils.set(Consts.REDIS_KEY_MAYCHAT_CAPTCHA_ANS + key, captcha.getCode(), Consts.TIME_1MIN * 10);
        HashMap<String, String> map = new HashMap<>();
        map.put("captcha", base64);
        map.put("key", key);
        return Result.success(map);
    }

    @PostMapping("/register")
    public Result register(@NotBlank String key,
                           @NotBlank @Email String email,
                           @Pattern(regexp = Consts.REGEX_PASSWORD) String password,
                           @NotBlank String nickName,
                           @NotBlank String captchaAns
    ) {
        key = Consts.REDIS_KEY_MAYCHAT_CAPTCHA_ANS + key;
        try {
            if (!captchaAns.equalsIgnoreCase((String) redisUtils.get(key)))
                throw new CaptchaException();
            userInfoService.register(email, password, nickName);
        } finally {
            redisUtils.del(key);
        }
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@NotBlank String key,
                        @NotBlank @Email String email,
                        @Pattern(regexp = Consts.REGEX_PASSWORD) String password,
                        @NotBlank String captchaAns
    ) {
        key = Consts.REDIS_KEY_MAYCHAT_CAPTCHA_ANS + key;
        try {
            if (!captchaAns.equalsIgnoreCase((String) redisUtils.get(key)))
                throw new CaptchaException();
            Map<String, Object> res = userInfoService.login(email, password);
            return Result.success(res);
        } finally {
            redisUtils.del(key);
        }
    }

}
